<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-08-18 16:40:16
 * @Last Modified by:   zhaozilong
 * @Last Modified time: 2020-11-09 15:46:28
 */

namespace app\admin\controller;
use app\BaseController;
use think\App;
use think\captcha\Captcha;
use think\Url;
use think\facade\View;

class Login extends BaseController {
	
    protected function initialize(): void {
		parent::initialize();
        //echo 'initialize';exit;
		$this->adminUserLogic = new \app\admin\logic\AdminUser();
    }
    
// 	public function __construct(App $app) {
// 	    parent::__construct($app);
// 	    //echo 3;exit;
// 	    
// 	}

	public function index() {
        $this->assign('adminCache', '000');
        
		//$result = $this->adminUserLogic->login('aaa', '123');
		
        return $this->fetch();
	}

	public function doLogin() {
		$username = input('post.username', '', 'pwEscape');
		$password = input('post.password', '', 'pwEscape');
		$rememberme = input('post.rememberme', '', 'intval');
		$data = [
			'username' => $username,
			'password' => $password,
		];
        try {
			$result = $this->validate($data, [
				'username' => 'require|min:1',
				'password' => 'require|length:5,32',
			],[
				'username.require' => '登录名不能为空',
				'username.min' => '登录名格式不正确',
				'password.require' => '请填写密码',
				'password.length' => '密码格式不正确',
			]);
			//echo '验证结果：';print_r($result);exit;
        }catch (\Exception $e) {
            $this->error($e->getMessage());
        }
		if ($result !== true) {
			// 验证失败 输出错误信息
			$this->error($result);
			exit;
		}
		//验证码
		if (0) {
			$result = $this->validate($data,[
				'captcha' => 'require',
			],[
				'captcha.require' => '请填写验证码',
			]);
			if (true !== $result) {
				// 验证失败 输出错误信息
				$this->error($result);
			}
			$captcha = new Captcha();
			if(!$captcha->check($data['captcha'],1)){
				$this->error('验证码错误');
			}
		}

		$result = $this->adminUserLogic->login($data['username'], $data['password'], $rememberme);
		//print_r($result);exit;

		if ($result['code'] == 200) {
			$uid = !empty($result['data']['uid']) ? $result['data']['uid']:0;
			$this->success('登录成功', url('admin/index/index'));
		} elseif ($result['code'] == 500) {
			$this->error($result['msg']);
		} else {
			$this->logout();
		}
	}

	
	/**
	 * 退出登录
	 * @return [type] [description]
	 */
	public function logout() {
		$this->adminUserLogic->logout();

		$this->redirect('admin/login/index');
	}

	//图片验证码
	public function verify_img($id = 1){
		$captcha = new Captcha((array)config('captcha'));
		return $captcha->entry($id);
	}

}